<template>
  <q-page class="q-pa-md wrapBox">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-image src="/svgs/titleIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'data-process' }">数据中心</el-breadcrumb-item>
        <el-breadcrumb-item><span style=" color: #333;">数据处理</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="contentBox_title">创建数据处理</div>
      <div class="contentBox">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="ruleFormRules" label-width="140px" style="max-width: 45%">
          <el-form-item label="名称：" prop="title">
            <el-input v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="描述：">
            <el-input
              v-model="ruleForm.desc" type="textarea"
              show-word-limit maxlength="100"
              :rows="5" />
          </el-form-item>
          <el-form-item label="场景类别：">
            合成生物数据处理
          </el-form-item>
          <el-form-item label="数据处理类型：" prop="prefix">
            <el-select v-model="ruleForm.prefix" placeholder="选择处理类型" popper-class="dropdown">
              <el-option label="序列去冗余" value="sequence" @click="getProcessAlgorithmId" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="ruleForm.prefix" label="参数配置项：" prop="parameters">
            <el-row :gutter="20" style="width: 100%;">
              <el-col :span="9">
                <div class="grid-content ep-bg-purple borderBox" v-for="(item, value) in parametersObj" :key="value">
                  {{ value }}
                </div>
              </el-col>
              <el-col :span="1" style="text-align: center;">
                <div v-for="(item, index) in parametersObj" :key="index">=</div>
              </el-col>
              <el-col :span="9">
                <div class="grid-content ep-bg-purple borderBox rightBox" v-for="(val, key) in parametersObj" :key="key">
                  <input class="inputBox" type="text" :value="val.default" @blur="changeText($event, key)" spellcheck="false">
                </div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="输入：" prop="source_dataset">
            <el-form-item prop="source_dataset" class="selectClass">
              <el-select v-loadMore="getMoreData" v-model="ruleForm.source_dataset" placeholder="请选择数据集名称" class="more-select" popper-class="more_dropdown_select" style="margin-right: 20px;">
                <el-option v-for="item in optionsList" :key="item.id" :label="item.title" :value="item.id" @click="getDataVersion(item.id,'1')" />
                <div v-if="loadingMoreState" class="selectMoreData">
                  <el-icon class="is-loading">
                    <Loading />
                  </el-icon>加载更多
                </div>
              </el-select>
            </el-form-item>
            <el-form-item prop="source_dataset_version" v-if="ruleForm.source_dataset">
              <el-select  v-loadData="getMoreVersion"  class="more-select" popper-class="more_select_Data" v-model="ruleForm.source_dataset_version" placeholder="请选择数据集版本">
                <el-option v-for="item in optionsList1" :key="item.id" :label="item.title" :value="item.id" />
                <div v-if="loadingMoreVersion" class="selectMoreData">
                  <el-icon class="is-loading">
                    <Loading />
                  </el-icon>加载更多
                </div>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="输出：" prop="source_dataset" v-if="ruleForm.source_dataset">
            <el-form-item prop="source_dataset">
              <el-select v-model="ruleForm.source_dataset" style="margin-right: 20px;" popper-class="dropdown">
                <el-option :disabled="true" v-for="item in optionsList" :key="item.id" :label="item.title" :value="item.id" @click="getDataVersion(item.id)" />
              </el-select>
            </el-form-item>
            <el-form-item prop="dest_version_title">
              <el-input v-model="ruleForm.dest_version_title" placeholder="请输入版本名称" />
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <div class="row" style="justify-content: flex-end;margin-top: 10px;background-color: #fff;padding: 10px 0 ">
        <el-button @click="resetForm(ruleFormRef)" style="background-color: #fff">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          完成
        </el-button>
      </div>
    </div>
  </q-page>
</template>

<script setup lang="ts">

import { ref, reactive, computed } from 'vue'
import { Obj } from '@popperjs/core';
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
import vLoadMore from 'src/utils/loadMore';
import vLoadData from 'src/utils/LoadMoreData';
import {
  getProcessAlgorithmIdHandle, //获取算法id
  getMlParametersHandle, //获取超参数
  getDatasetList, versionManage, //获取数据集列表
  createProcess, //创建数据处理任务
  validateProcessTitle,//验证任务名称是否重复
} from "src/api/dataset";
import {DisposableSet} from "@antv/x6";
import from = DisposableSet.from;
const ruleFormRef = ref();
const router = useRouter();
const projectId = router.currentRoute.value.params.project_id
const ruleForm = reactive({
  title: '',
  prefix: '',
  desc: '',
  source_dataset: '',
  source_dataset_version: '',
  dest_version_title: ''
});
const pageData = ref({page: 1});
const pageData1 = ref({page: 1});
const optionsList = ref(<any>[]);
const optionsList1 = ref(<any>[]);
const versionId = ref(0);
const loadingMoreState = ref(false);
const loadingMoreVersion = ref(false);
const validateDestVersionTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入版本名称'));
    return;
  }
  if (value.length > 0 ) {
    const data = JSON.parse(JSON.stringify(optionsList1.value));
    const filterdata = data.filter( (item:any) => item.title === value );
    if( filterdata.length > 0 ){
      callback(new Error('输入的版本名称不能和已有的数据集版本名称相同'));
      return;
    }
    callback();
  }
  callback();
};
const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('数据处理名称不能为空'));
    return;
  }
  let params = {
    process_name: ruleForm.title,
  };
  validateProcessTitle(projectId, params)
    .then((res: any) => {
      if (res.data.msg) {
        callback(new Error(res.data.msg));
      }
      callback();
    })
    .catch((err: any) => {
      callback(new Error('校验接口报错'));
    });
};
const ruleFormRules = reactive({
  title: [{ required: true, validator: validateTitle, trigger: 'blur' }],
  version: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
  prefix: [{ required: true, message: '类型不能为空', trigger: 'change' }],
  parameters: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (value === '') {
          callback();
        } else {
          const objData = JSON.parse(JSON.stringify(parametersObj.value));
          if (!Object.keys(objData).every(key => objData[key].default !== '')) {
            callback(new Error('参数配置列表项不能为空'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur',
    },
  ],
  source_dataset: [{ required: true, message: '数据集名称不能为空', trigger: 'blur' }],
  source_dataset_version: [{ required: true, message: '数据集版本不能为空', trigger: 'blur' }],
  dest_version_title: [{ required: true,  validator: validateDestVersionTitle, trigger: 'blur' }],
});
const parametersObj = ref(null);
// const onSubmit = () => { validator: validateTitle
//   console.log('submit!')
// }

const dataSetList = ref({
  count: 0,
  results: <any>[]
});
const versionList = ref({
  count: 0,
  results: <any>[]
});//存放版本列表数据
let modelId = ref(0);//算法id


const getMoreData = async () => {
  if (pageData.value.page < (dataSetList.value.count) / 10) {
    loadingMoreState.value = true
    pageData.value.page++;
    initPageEvent();
    loadingMoreState.value = false
  }
}
const getMoreVersion = async ()=>{
  if (pageData1.value.page < (versionList.value.count) / 10) {
    loadingMoreVersion.value = true
    pageData1.value.page++;
    getDataVersion(versionId.value,'2');
    loadingMoreVersion.value = false
  }
}

//页面初始化事件
initPageEvent();
function initPageEvent(){
  //获取数据集列表
  let obj: any = { dataset_type: 'TimeSeries' };
  obj = Object.assign(obj, pageData.value);
  getDatasetList(projectId,obj).then( (res:any) =>{
    dataSetList.value = res.data;
    optionsList.value = optionsList.value.concat(dataSetList.value.results)
  })
}
function getDataVersion(id:any,nums:string){
  versionId.value = id;
  if( nums === '1' ){
    pageData1.value.page = 1;
    optionsList1.value = [];
  }
  versionManage(projectId,id,pageData1.value).then( (res:any) =>{
    versionList.value = res.data;
    optionsList1.value = optionsList1.value.concat(versionList.value.results)
  })
}

//获取算法id
function getProcessAlgorithmId(){
  getProcessAlgorithmIdHandle(projectId,{ prefix: ruleForm.prefix }).then( (res:any) =>{
    modelId.value = res.data.id;
  });
  //获取超参数列表
  getMlParametersHandle(projectId,{ prefix: ruleForm.prefix }).then( (res:any) =>{
    parametersObj.value = res.data;
    if( ruleForm.prefix === 'sequence' ){
      delete parametersObj.value.data_path;
    }
  })
}
// let allDefaultsEmpty = ref(false);
// allDefaultsEmpty.value = computed(() => {
//   if (!parametersObj.value) {
//     return false;
//   }
//   const obj = JSON.parse(JSON.stringify(parametersObj.value));
//   return !Object.keys(obj).every((key) => obj[key].default === '');
// });

function changeText(e: any, key: string) {
  // const obj = JSON.parse(JSON.stringify(parametersObj.value));
  // // allDefaultsEmpty.value = !Object.keys(obj).every((key) => obj[key].default === '');
  parametersObj.value[key].default = e.target.value;
}
// 处理数组，合并为object
const mergeArr = (arr1: Array<string>, arr2: Array<string>) => {
  let newObj: Obj = {}
  arr1.forEach((item, index) => {
    newObj[item] = arr2[index]
  })
  return newObj
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let obj = JSON.parse(JSON.stringify(parametersObj.value));
      const ml_parameters = Object.keys(obj).reduce((acc, key) => {
        if (obj[key].hasOwnProperty('default')) {
          acc[key] = obj[key].default;
        }
        return acc;
      }, {});
      if( ruleForm.prefix === 'sequence' ){
        const source = optionsList1.value.find( (item:any) => item.id === ruleForm.source_dataset_version);
        const data_file = JSON.parse(JSON.stringify(source)).data_file;
        ml_parameters.data_path = '../'+data_file.split('/').pop();
        delete ml_parameters.output;
      }
      const dataset = optionsList.value.find( (item:any) => item.id === ruleForm.source_dataset);
      const datasetType = dataset ? dataset.dataset_type : null;
      const params = {
        ml_parameters,
        model: modelId.value,
        dest_version_title: ruleForm.dest_version_title,
        source_dataset: ruleForm.source_dataset,
        source_dataset_version: ruleForm.source_dataset_version,
        title: ruleForm.title,
        dataset_type: datasetType
      }
      createProcess(projectId,params).then( (res:any) =>{
        router.push({ name: 'data-process', params: { project_id: projectId } })
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  router.push({ name: 'data-process', params: { project_id: projectId } })
}

</script>

<style scoped lang="scss">
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;
    ::v-deep .el-breadcrumb{
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}

//下拉框背景颜色
.dropdown {
  .el-select-dropdown__list{
    margin: 0!important;
  }
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background: #3d5ce41a;
    color: #3d5ce4;
    font-weight: 400;
    font-size: 14px;
    text-align: left;
  }
}

.borderBox {
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #cccccc;
  border-bottom: none;
  padding: 0 5px;
  word-break: break-all;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;

  &:first-child {
    border-radius: 4px 4px 0 0;
  }

  &:last-child {
    border-bottom: 1px solid #cccccc;
    border-radius: 0 0 4px 4px;
  }
}

.inputBox {
  width: 100%;
  border: none;
  height: 30px;
  border: none;
  color: #585858;

  &:focus {
    border: none;
    outline: none;
  }
}
//input type为textarea去掉右下角的两个杠
::v-deep textarea {
  resize: none !important;
}

//面包屑斜杆
::v-deep .el-breadcrumb__separator{
  font-size: 12px!important;
  color: #c9cdd4!important;
  margin-top: 2px!important;
}
:deep(.el-input__inner::placeholder),:deep(.el-textarea__inner::placeholder){
  color: #cccccc;
  font-size: 14px;
  font-weight: 400;
}
::v-deep .el-breadcrumb__inner.is-link, .el-breadcrumb__inner a{
  font-weight: normal!important;
}
</style>
